<template>
  <div class="echarts-box" :style="{ width, height }">
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div class="echarts" ref="oEcharts" :id="randomString()"></div>
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import { randomString } from "@/utils/tools";
//按需引入
import { onMounted, onUnmounted, ref, watch, getCurrentInstance } from "vue";

//  用于控制  tooltip 自动轮播
const tools = (window as any).tools;

const props = defineProps({
  option: { type: Object, default: () => ({}) },
  loop: { type: Boolean, default: false },
  width: { type: String, default: "100%" },
  height: { type: String, default: "100%" },
});

const emit = defineEmits(["change"]);

//  获取组件实例
const internalInstance = getCurrentInstance();
const { echarts } = internalInstance!.appContext.config.globalProperties;

let myChart: any = null;
const oEcharts = ref<HTMLDivElement | null>(null);

//  创建 echarts
function createEcharts() {
  //  重新绘制 echarts 图表
  disposeEcharts();
  if (!props.option) return;

  if (!oEcharts.value) return;

  myChart = echarts.init(oEcharts.value);
  if (!myChart) return;

  myChart && myChart.setOption(props.option, true);
  emit("change", myChart);

  if (props.option.series && props.loop) {
    tools.loopShowTooltip(myChart, props.option, { loopSeries: true });
  }
}

//  销毁 Echarts
function disposeEcharts() {
  if (!myChart) return;
  window.removeEventListener("resize", myChart.resize);
  myChart.dispose();
  myChart = null;
}

//  监听 options的变化 重新绘制 echarts 图表
watch(
  () => props.option,
  (val, oldVal) => {
    createEcharts();
  }
);

onMounted(() => {
  createEcharts();
});

//  销毁组件 - 取消挂载
onUnmounted(() => {
  disposeEcharts();
});
</script>

<style lang="scss" scoped>
.echarts {
  width: 100%;
  height: 100%;
}

.echarts-box {
  position: relative;
  width: 100%;
  height: 100%;
  // border: 1px solid red;
  box-sizing: border-box;
}

.tip {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36px;
}
</style>
